$(document).ready (function() {

  // Item variables setup
  var itemIndex = parseInt(($('#addItem').attr('title')), 10);
  $('#addItem').removeAttr('title');

  // Add delete function to already created items
  $('.removeItem').click(function() {
    var erasedItem = parseInt($(this).attr('id').match(/[0-9]+/g).join(''), 10);
    var td = $('#totalItem' + erasedItem);
    var totalItem = td.attr("textContent");;
    var totalSale = $('#totalSale').val();
	totalSale = parseFloat(totalSale) - parseFloat(totalItem);
	$('#totalSale').val(totalSale.toFixed(2));
    $('#itemNumber' + erasedItem).remove();
    itemSequentialId(erasedItem);
  });

  // Adds a new item
  $('#addItem').click(function() {
	  
	var productId = $('#productId').val();
	var productName = $('#productName').val();
	var productPrice = $('#price').val();
	var productAmount = $('#amount').val();
	var total = $('#total').val();

	var validationOK = validateItem(productId, productPrice, productAmount, total);
	if (validationOK) {
	  var totalSale = $('#totalSale').val();
	  var totalAccount = $('#totalAccount').val();
	  totalSale = parseFloat(totalSale) + parseFloat(total);
	  totalAccount = parseFloat(totalAccount) + parseFloat(total);
	  $('#totalSale').val(totalSale.toFixed(2));
	  $('#totalAccount').val(totalAccount.toFixed(2));
      itemIndex += 1;
      var newItem = "<tr id='itemNumber" + itemIndex + "'><td name='index'>" + itemIndex
    		      + "</td><td name='id'>" + productId
                  + "</td><td name='name'>" + productName
                  + "</td><td name='price'>" + productPrice 
                  + "</td><td name='amount'>" + productAmount
                  + "</td><td id ='totalItem" + itemIndex + "' name='total'>" + total
                  + "</td><td name='button'><button type='button' class='removeItem' id='remItem"+itemIndex+"'>Delete</button></td></tr>";
      $('#itemList tbody:last').append(newItem);
      $('#remItem' + itemIndex).click(function() {
        var erasedItem = parseInt($(this).attr('id').match(/[0-9]+/g).join(''), 10);
        var td = $('#totalItem' + erasedItem);
        var totalItem = td.attr("textContent");;
        var totalSale = $('#totalSale').val();
        var totalAccount = $('#totalAccount').val();
    	totalSale = parseFloat(totalSale) - parseFloat(totalItem);
    	totalAccount = parseFloat(totalAccount) - parseFloat(totalItem);
    	$('#totalSale').val(totalSale.toFixed(2));
    	$('#totalAccount').val(totalSale.toFixed(2));
        $('#itemNumber' + erasedItem).remove();
        itemSequentialId(erasedItem);
      });
	}
  });

  // Renumbers the ids of the items to keep them ordered.
  var itemSequentialId = function(erasedItem) {
    if (erasedItem === itemIndex) {
      itemIndex -= 1;
    } else {
      $('#itemList tr').each(function() {
    	var tr = $(this);
    	if (tr.attr('id') != "") {
          var thisItem = parseInt(tr.attr('id').match(/[0-9]+/g).join(''), 10);
          if (thisItem > erasedItem) {
            var newItem = thisItem - 1;
            //Replace id on all elements.
            tr.attr("id", "itemNumber" + newItem);
            $('#totalItem' + thisItem).attr("id", "totalItem" + newItem);
            $('#remItem' + thisItem).attr("id", "remItem" + newItem);
            tr.find('td').each(function() {
		      var td = $(this);
		      if (td.attr("name") == "index") {
	  		    td.attr("textContent", newItem);
			  }
            });
          }
    	}
      });
      itemIndex -= 1;
    }
  };
  $('#submit').click(function(e) {
	var items = extractItems();
	var i = 0;
	var input;
	while (i < items.length ) {
		var row = items[i];
		input = $("<input>").attr("type", "hidden").attr("name", "items[" + i +"].productId").val(row[0]);
		$('#addSale').append($(input));
		input = $("<input>").attr("type", "hidden").attr("name", "items[" + i +"].price").val(row[1]);
		$('#addSale').append($(input));
		input = $("<input>").attr("type", "hidden").attr("name", "items[" + i +"].amount").val(row[2]);
		$('#addSale').append($(input));
		i++;
	}
	if (i == 0) {
		alert("An item must be iserted to the table.");
	}
	$('#theCustomerId').val($('#customerId').val());
	$('#theCustomerName').val($('#customerName').val());
	$('#theCustomerCuil').val($('#customerCuil').val());
	var validationOK = (i > 0 && validateForm());
	if (!validationOK) {
		e.preventDefault();
	}
  });

  extractItems = function() {
	  var result = new Array();
	  $('#itemList tr').each(function() {
		  var tr = $(this);
		  if (tr.attr('id') != "") {
	        var i = parseInt(tr.attr('id').match(/[0-9]+/g).join(''), 10);
		    var id = "0";
		    var price = "0";
		    var amount = "0";
		    var total = "0";
		    tr.find('td').each(function() {
		      var td = $(this);
  		      if (td.attr("name") == "id") {
  		    	id = td.attr("textContent");
		      } else if (td.attr("name") == "price") {
		    	price = td.attr("textContent");
			  } else if (td.attr("name") == "amount") {
			    amount = td.attr("textContent");
			  } else if (td.attr("name") == "total") {
			    total = td.attr("textContent");
			  }
		    });
		    var row = [id, price, amount, total];
		    result[i]=row;
		  } 
	});
	return result;
  }

  validateItem = function(productId, productPrice, productAmount, total) {
	  if (productId == "" || productId == "0") {
		  alert("Product Id must be filled.");
		  return false;
      }
	  if (productPrice == "") { 
		  alert("Product price must be filled.");
		  return false;
	  } else if (isNaN(productPrice)) {
		  alert("Product price is not a number.");
          return false;
      } else {
    	  var price = parseFloat(productPrice);
    	  if (price <= 0) {
    		  alert("Product price must be greater than 0.");
    		  return false;
    	  }
      }
	  if (productAmount == "") { 
		  alert("Amount must be filled.");
		  return false;
	  } else if (isNaN(productAmount)) {
		  alert("Amount is not a number.");
          return false;
      } else {
    	  var amount = parseFloat(productAmount);
    	  if (amount <= 0) {
    		  alert("Product amount must be greater than 0.");
    		  return false;
    	  }
      }
	  if (total == "") {
    	  alert("Product total price must be filled.");
    	  return false;
      } else if (isNaN(total)) {
    	  alert("Product total price is not a number.");
    	  return false;
      } else {
    	  var prodTotal = parseFloat(total);
    	  if (prodTotal <= 0) {
    		  alert("Product total must be greater than 0.");
    		  return false;
    	  }
      }
	  return true;
  }
  
  validateForm = function() {
	  if ($('#paymentSelected0')[0].checked) {
		  var amountCheck = parseFloat($('#amountCheck').val());
		  if (amountCheck <= 0) {
			  alert("Check amount must be greater than 0.");
			  return false;
		  }
		  var numCheck = $('#numCheck').val();
		  if (numCheck == "") {
			  alert("Check number can not be empty.");
			  return false;
		  }
		  var bankCheck = $('#bankCheck').val();
		  if (bankCheck == "") {
			  alert("Check bank can not be empty.");
			  return false;
		  }
		  var dateCheck = $('#dateCheck').val();
		  if (dateCheck == "") {
			  alert("Check date can not be empty.");
			  return false;
		  }
	  } else {
		  if ($('#paymentSelected2')[0].checked) {
		    var customerId = parseInt($('#customerId').val());
		    if (customerId <= 0) {
		    	alert('Customer must be selected when using customer account.');
		    	return false;
		    }
		  }
	  }
	  return true;
  }
  
  
  $('#price').change(function() {
	  var price = $('#price').val();
	  var amount = $('#amount').val();
	  var total = price*amount;
	  $('#total').val(total.toFixed(2));
  });
  
  $('#amount').change(function() {
	  var price = $('#price').val();
	  var amount = $('#amount').val();
	  var total = price*amount;
	  $('#total').val(total.toFixed(2));
  });
  
  $('#productName').focus(function(){
	  $('#myProductTable').toggle();
		return false;
  });
  
  $('#customerName').focus(function(){
	  $('#myCustomerTable').toggle();
		return false;
  });

  //On check Selected
  $('#paymentSelected0').click(function() {
	    if (this.checked) {
	    	$('#checkOptions').css("display", "block");
	    } else {
	    	$('#checkOptions').css("display", "none");
	    }
	});

  //On Credit card selected
  $('#paymentSelected1').click(function() {
	    if (!this.checked) {
	    	$('#checkOptions').css("display", "block");
	    } else {
	    	$('#checkOptions').css("display", "none");
	    }
	});

  //On client account selected
  $('#paymentSelected2').click(function() {
	    if (!this.checked) {
	    	$('#checkOptions').css("display", "block");
	    } else {
	    	$('#checkOptions').css("display", "none");
	    }
	});

  //On Cash selected
  $('#paymentSelected3').click(function() {
	    if (!this.checked) {
	    	$('#checkOptions').css("display", "block");
	    } else {
	    	$('#checkOptions').css("display", "none");
	    }
	});

  //On Debit card selected
  $('#paymentSelected4').click(function() {
	    if (!this.checked) {
	    	$('#checkOptions').css("display", "block");
	    } else {
	    	$('#checkOptions').css("display", "none");
	    }
	});

  
  $(function() {
    $("#dateCheck").datepicker({
     dateFormat: 'dd-mm-yy',
     changeMonth: true,
     changeYear: true,
     yearRange: "-1:+90"});
  });
 
  $('#amountCash').change(function() {
	 updateAmounts();
  });
  
  $('#amountCreditCard').change(function() {
		 updateAmounts();
  });

  $('#amountDebitCard').change(function() {
		 updateAmounts();
  });
  
  $('#amountCheck').change(function() {
		 updateAmounts();
  });
  
  updateAmounts = function(){
	  var debit = parseFloat($('#amountDebitCard').val());
	  var credit = parseFloat($('#amountCreditCard').val());
	  var check = parseFloat($('#amountCheck').val());
	  var cash = parseFloat($('#amountCash').val());
	  var payed = debit + credit + check + cash;
	  var total = parseFloat($('#totalSale').val());
	  $('#totalPayed').val(payed.toFixed(2));
	  $('#totalAccount').val((total - payed).toFixed(2));
  }
});


